﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace NTQOnlineExam.Services.Infrastructure.Encryption
{
    public class CryptographyUtilities
    {
        /// <summary>
        /// This function creates a md5 hash string from input string.
        /// This function can be used if you need to create a scenario where 
        /// you have to be sure the posted values comes from a trusted source.
        /// </summary>
        /// <param name="unencryptedString">String to hash.</param>
        /// <returns>Returns a md5 checksum of the input string.</returns>
        public static string CreateMD5Hash(string unencryptedString)
        {
            UTF8Encoding UTF8Encoder = new UTF8Encoding();
            byte[] aryBytes = UTF8Encoder.GetBytes(unencryptedString);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] bHashedData = md5.ComputeHash(aryBytes);
            return BitConverter.ToString(bHashedData).Replace("-", "");
        }

        /// <summary>
        /// Creates a SHAHashed version of the supplied string
        /// </summary>
        /// <param name="unencryptedString"></param>
        /// <returns></returns>
        public static string CreateSHAHash(string unencryptedString)
        {
            UTF8Encoding UTF8Encoder = new UTF8Encoding();
            byte[] aryBytes = UTF8Encoder.GetBytes(unencryptedString);
            SHA512Managed sha = new SHA512Managed();
            byte[] bHashedData = sha.ComputeHash(aryBytes);
            return BitConverter.ToString(bHashedData).Replace("-", "");
        }

        /// <summary>
        /// Creates a HMac hash from input string.
        /// </summary>
        /// <returns></returns>
        public static string CreateHMacHash(string key, string unencryptedString)
        {
            var encoding = new UTF8Encoding();
            var keyByte = FromHex(key);
            //byte[] keyByte = encoding.GetBytes(key);

            var hmacsha256 = new HMACSHA256(keyByte);
            byte[] messageBytes = encoding.GetBytes(unencryptedString);
            var bHashedData = hmacsha256.ComputeHash(messageBytes);

            return BitConverter.ToString(bHashedData).Replace("-", "");
        }

        public static byte[] FromHex(string hex)
        {
            hex = hex.Replace("-", "");
            var raw = new byte[hex.Length / 2];
            for (int i = 0; i < raw.Length; i++)
            {
                raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
            }
            return raw;
        }

    }
}
